from schema import session, schema
import searchtext
import util
from Cheetah.Template import Template
from datetime import datetime
from cherrypy import request 
from UIBase import UIBase

class UIObject(UIBase):
    def __init__(self, superclass):
        UIBase.__init__(self)
        self.superclass = superclass
        self.schema_object = schema.get(self.superclass.table_schema.__tablename__)
        self.query_object = None
        self.name_template = 'template1.tmp'
        self.context = {}
        
    def delete(self, wargs):
        try:
            list_checked_item = wargs.get('check_schema_name')
            for id_object in list_checked_item:
                edit_object = session.query(self.superclass.table_schema).filter_by(id=id_object).one() 
                session.delete(edit_object)
            session.commit()
        except Exception, error:
            session.rollback()
            self.msg = error
        else:
            self.msg = 'Delecao de objeto %s feita com sucesso' % self.schema_object
    
    def new(self, edit_wargs):
        try:
            edit_object = self.superclass.table_schema(**edit_wargs)
            session.add(edit_object)
            session.commit()
        except Exception, error:
            session.rollback()
            self.msg = error
        else:
            self.msg = 'Criacao de objeto %s feita com sucesso' % self.schema_object
    def edit(self, wargs, edit_wargs):
        try:
            id_object = wargs['id'] 
            edit_object = session.query(self.superclass.table_schema).filter_by(id=id_object).one() 
            for k,v in edit_wargs.items():
                setattr(edit_object, k, v)
            session.add(edit_object)
            session.commit()
        except Exception, error:
            session.rollback()
            self.msg = error
        else:
            self.msg = 'Edicao de objeto %s feita com sucesso' % self.schema_object
    
    def response(self):
        self.context.update(dict(error=self.msg))
        return str(Template(open(self.name_template).read(), namespaces=self.context ) )
    
    def _edit_wargs(self, wargs):
        edit_wargs = {}
        for col in [col for col in self.schema_object.columns if type(col.type) in [sqlalchemy.Date, sqlalchemy.DateTime]]:
            column_name = col.name
            if type(col.type) is sqlalchemy.Date:
                if wargs.get(column_name):
                    wargs[column_name] = datetime.strptime(wargs.get(column_name), model.FORMAT_DATE)  
            elif type(col.type) is sqlalchemy.DateTime:
                if wargs.get(column_name):
                    wargs[column_name] = datetime.strptime(wargs.get(column_name), model.FORMAT_DATE_TIME)  
        for column_name in [col.name for col in self.schema_object.columns if not col.primary_key ]:
            if wargs.get(column_name):
                edit_wargs[column_name] = wargs.get(column_name)
        return edit_wargs
    
    def request_post(self, wargs):
        try:
            if wargs['action'] in ['new', 'edit']:
                edit_wargs = self._edit_wargs(wargs)

            if wargs['action'] == 'delete':
                return self.delete(wargs)
            elif wargs['action'] == 'new':
                return self.new(edit_wargs)
            elif wargs['action'] == 'edit':
                return self.edit(wargs, edit_wargs)
            else:
                return self.response()
        except Exception, error:
            self.msg = error
            return self.response()
    
    def index(self, **wargs):
        self.msg = ''
        self.query_object = session.query(self.superclass.table_schema).order_by(self.superclass.table_schema.id)
        self.context = {'schema_object': self.schema_object,
                       'schema': schema,
                       'query_object': self.query_object,
                       'error': self.msg,
                       'util': util,
                       'wargs': wargs}

        if request.method == 'GET' and wargs.get('search'):
            search_string = wargs.get('search')
            search_text = searchtext.SearchText(session, self.superclass.table_schema, self.schema_object)
            query_object = search_text.search(search_string)
            self.context.update(dict(query_object=query_object))

        if request.method == 'POST':
            return self.request_post(wargs)
        else:
            return self.response()
        
    index.exposed = True
